package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //1.获取session
//        HttpSession session = request.getSession();
        //获取请求头中的token
        String token = request.getHeader("authorization");


        if (StrUtil.isBlank(token)){
          return true;
        }

        // 2.提取session中的用户
//        Object user = session.getAttribute("user"); //从session中获取用户信息

        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries("login:token" + token);
        // 3.判断用户是否存在
        if (userMap.isEmpty()){
         return true;
        }
        //5.存在，保存在threadLocal
//        UserHolder.saveUser((UserDTO) user);

        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        UserHolder.saveUser(userDTO);//保存用户信息

        //6.刷新token有效期
        stringRedisTemplate.expire("login:token"+token,30, TimeUnit.MINUTES);

        return true;
    }

    //销毁用户信息，避免内存泄漏
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
